import { defineStore } from 'pinia'
import { useDark, useWindowSize } from '@vueuse/core'
import ColorUtils from '@/utils/ColorUtils'

/**
 * 系统设置
 * 系统参数
 */
export const useSystemStore = defineStore('system', () => {
  const { width, height } = useWindowSize()

  //是否显示菜单抽屉
  const showDrawer = ref(width.value >= 992)
  //布局 'BiDirectionalSplitLayout'|'SplitLevelLayout'|'StackedLayout'|‘MobileLayout’
  const layoutRef = ref('SplitLevelLayout')
  //菜单背景颜色
  const menuBackgroundColorRef = ref('#545c64')
  //菜单文字颜色
  const menuTextColorRef = ref('#fff')
  //菜单激活时的颜色
  const menuActiveTextColorRef = ref('#409eff')
  const loadingCount = ref(0)
  //根据当前宽度计算布局
  const layout = computed(() => {
    if (width.value < 992) {
      //小屏幕只有MobileLayout布局支持
      return 'MobileLayout'
    }
    if (width.value < 1200 && layoutRef.value === 'StackedLayout') {
      //此大小不支持StackedLayout
      return 'SplitLevelLayout'
    }
    return layoutRef.value
  })
  //小屏幕不显示菜单时，大屏幕折叠菜单，折叠左侧菜单
  const isCollapse = computed(() => !showDrawer.value)
  //是否使用黑暗模式
  const isDark = useDark()
  const menuBackgroundColor = computed(() => getColor(isDark.value, menuBackgroundColorRef.value))
  const menuTextColor = computed(() => getColor(isDark.value, menuTextColorRef.value))
  const menuActiveTextColor = computed(() => getColor(isDark.value, menuActiveTextColorRef.value))
  const getDarkColor = (color: string, level: number = 0.8) => {
    if (isDark.value) {
      return ColorUtils.getDarkColor(color, level)
    } else {
      return color
    }
  }
  const getLightColor = (color: string, level: number = 0.8) => {
    if (!isDark.value) {
      return color
    } else {
      return ColorUtils.getLightColor(color, level)
    }
  }
  const openLoading = () => {
    loadingCount.value++
  }
  /**
   *
   * @param changeCount 不传，默认为1，传负数将重置计数器
   */
  const closeLoading = (changeCount: number = 1) => {
    let val = loadingCount.value - changeCount
    if (changeCount < 0) {
      val = 0
    }
    //防止变成负数
    loadingCount.value = val < 0 ? 0 : val
  }
  const isLoading = computed(() => loadingCount.value > 0)
  return {
    showDrawer,
    layoutRef,
    layout,
    isCollapse,
    width,
    height,
    menuBackgroundColorRef,
    menuTextColorRef,
    menuActiveTextColorRef,
    menuBackgroundColor,
    menuTextColor,
    menuActiveTextColor,
    isDark,
    openLoading,
    closeLoading,
    isLoading,
    getDarkColor
  }
})

function getColor(isDark: boolean, color: string): string {
  if (isDark) {
    return ''
  } else {
    return color
  }
}
